import {defineStore} from 'pinia';
import {doLoginApi} from '@/api/login';

interface State {
    menuList: Array<any> | null;
    token: string | null;
    userInfo: any;
}

const usePermission = defineStore('permission', {
    state: (): State => {
        return {
            menuList: null,
            token: null,
            userInfo: null,
        };
    },
    actions: {
        setMenuList(menuList: State['menuList']) {
            this.menuList = menuList;
        },
        setToken(token: State['token']) {
            this.token = token;
        },
        setUserInfo(userInfo: State['userInfo']) {
            this.userInfo = userInfo;
        },
        // 登录操作
        handleLogin(form: any) {
            return new Promise(async (resolve, reject) => {
                try {
                    const res = await doLoginApi(form);
                    if (res.data) {
                        const data = res.data as any;
                        this.setToken(data.token as any);
                        this.setUserInfo(data);
                    }
                    resolve(true);
                } catch (error) {
                    console.error(error);
                    reject();
                }
            });
        },
    },
    persist: {
        key: 'permission',
        storage: window.sessionStorage,
    },
});

export default usePermission;
